package com.example.pageexample.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;

import com.example.pageexample.database.Picture;
import com.example.pageexample.database.PictureHelper;
import com.example.pageexample.page.Constants;
import com.example.pageexample.page.PageSourceFactory;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 基于PagedList获取数据
 * @author mailanglideguozhe
 * @date 20210710
 */
public class PictureViewModel extends ViewModel {
    private static final String TAG = "PictureViewModel";
    //监听当前列表数据
    private LiveData<PagedList<Picture>> mPagedListLiveData;
    //数据库总长度监听
    private MutableLiveData<Integer> mCountLiveData = new MutableLiveData<>();
    public PictureViewModel() {
        //设置分页控件的配置参数
        PagedList.Config config = new PagedList.Config.Builder()
                .setPageSize(Constants.PAGE_SIZE)//每页大小
                .setPrefetchDistance(4)//设置距离底部还有多少条数据时开始加载下一页
                .setEnablePlaceholders(true)//设置占位
                .setInitialLoadSizeHint(Constants.PAGE_SIZE *2)//设置首次加载的长度
                .build();
        mPagedListLiveData = new LivePagedListBuilder<>(new PageSourceFactory(), config).build();
    }

    public LiveData<PagedList<Picture>> getPagedListLiveData() {
        return mPagedListLiveData;
    }

    public MutableLiveData<Integer> getCountLiveData() {
        return mCountLiveData;
    }

    /**
     * 请求计算列表总长度
     */
    public void requestTotalCount(){
        PictureHelper.getInstance().requestTotalCount().subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer integer) {
                mCountLiveData.postValue(integer);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }
}
